package com.dtzhejiang.social.supervision.risk.engine.server.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.job.builder.SimpleJobBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.TaskletStepBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 任务后门
 * @Author: Lexus
 * @Date: 2020/12/8 10:00
 */
@RestController
@Slf4j
public class BackendController {

    @Autowired
    JobRepository jobRepository;
    @Autowired
    JobLauncher jobLauncher;
    @Autowired
    JobBuilderFactory jobBuilderFactory;
    @Autowired
    StepBuilderFactory stepBuilderFactory;

    @Autowired
    private Map<String, SimpleJobBuilder> jobBuilderMap;

    @Autowired
    private Map<String, TaskletStepBuilder> taskletStepBuilderMap;

    @PostMapping("/task/step/retry")
    public void retryStep(@RequestBody String stepName) {
        try {
            jobLauncher.run(jobBuilderFactory.get("backend_custom"+stepName).start(taskletStepBuilderMap.get(stepName).build()).build(), new JobParametersBuilder().toJobParameters());
        }catch (Exception e){
            log.error("backend execute step {} fail", stepName, e);
        }
    }

    @PostMapping("/task/retry")
    public void retryTask(@RequestBody String taskName) {
        try {
            jobLauncher.run(jobBuilderMap.get(taskName).build(), new JobParametersBuilder().toJobParameters());
        }catch (Exception e){
            log.error("backend execute job {} fail", taskName, e);
        }
    }
}